//
//  FriendViewController.m
//  Light
//
//  Created by 骁唐 on 15/9/9.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//
#import "FriendViewController.h"
#import "People.h"
#import "PeopleGroup.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "constantDefinition.h"
#import "UserConfig.h"
#import "FriendDetailViewController.h"
#import "FriendTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "pinyin.h"
#import "ChineseString.h"
#import "LoginViewController.h"
@interface FriendViewController () <UITableViewDataSource, UITableViewDelegate,MBProgressHUDDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
@property (weak, nonatomic) IBOutlet UITableView *friendTableView;
//保存所有数据
@property (strong,nonatomic) NSArray *ary;
@property (strong,nonatomic) NSMutableArray *resArr;
@property (strong,nonatomic) NSMutableArray *nameArr;
@property (retain,nonatomic) NSMutableArray *indexArray;
@property (retain,nonatomic) NSMutableArray *LetterResultArr;

@end

@implementation FriendViewController
{
    UIAlertView *alert;
    NSDictionary *selectDic;
    NSArray *searchResults;
    NSMutableArray *searchNameArr;
    UISearchDisplayController *searchDisplayController;
    BOOL startSearch;
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    _resArr = [[NSMutableArray alloc]init];
    selectDic = [[NSDictionary alloc]init];
    _nameArr = [[NSMutableArray alloc]init];
    searchResults = [[NSArray alloc]init];
    searchNameArr = [[NSMutableArray alloc]init];
    [_friendTableView setSectionIndexBackgroundColor:[UIColor clearColor]];
    [_friendTableView setSectionIndexColor:[UIColor whiteColor]];
    
    MBPROGRESS_ALLOC;
    
    
    // Do any additional setup after loading the view.
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    [self getFriendList];
    [self judgeBackGroundTime];
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.indexArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [[self.LetterResultArr objectAtIndex:section] count];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 25)];
    
    headView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.3];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 25)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:17.0f];
    
    NSString *key = [self.indexArray objectAtIndex:section];
    titleLabel.text = key;
    [headView addSubview:titleLabel];
    
    return headView;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *friendID = @"friendCell";
    FriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:friendID];
    NSDictionary *cellDic = [[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    if ([[cellDic objectForKey:@"remarks"] isKindOfClass:[NSNull class]])
    {//remarks-备注   Name-昵称
        cell.friendName.text = @"";
    }
    else
    {
        cell.friendName.text = [cellDic objectForKey:@"remarks"];
    }
    if ([cellDic[@"headPortrait"] isKindOfClass:[NSNull class]])
    {//如果是空字段
    }
    else
    {
        [cell.friendImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/up/%@",SERVER_KEY,cellDic[@"headPortrait"]]] placeholderImage:[UIImage imageNamed:@"friend-head"]];//设置头像
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    selectDic = [[_LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    [self performSelector:@selector(dismissSelectCell) withObject:nil afterDelay:0.1];
    
    [self performSegueWithIdentifier:@"friendDetail" sender:nil];
}

- (void)dismissSelectCell {
    [_friendTableView deselectRowAtIndexPath:[_friendTableView indexPathForSelectedRow] animated:YES];
}

#pragma mark - 返回索引(数据源方法系统自动调用)
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.indexArray;
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}


#pragma mark 获取好友列表
- (void)getFriendList {
    [_mbProgressHud show:YES];
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    __weak FriendViewController *weakSelf = self;
    NSDictionary *dic = @{@"Token":[NSString stringWithFormat:@"%@",[userConfig getToken]]};
    //获取好友列表
    [httpManager POST:FRIEND_LIST parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"获取成功");
                  if ([dic[@"a"] intValue] == 1)
                  {
                      NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:dic[@"b"]];
                      weakSelf.resArr = [resDic mutableCopy];
                      //按首字母排序
                      [weakSelf.resArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                          NSDictionary *person1 = obj1;
                          NSDictionary *person2 = obj2;
                          //remarks-备注   Name-昵称
                          NSString *pName1 = person1[@"remarks"];//取Name-昵称字段；需换成  备注字段
                          NSString *pName2 = person2[@"remarks"];//取Name-昵称字段；需换成  备注字段
                          return [pName1 compare:pName2 options:NSCaseInsensitiveSearch];
                      }];
                      
                      for ( int i = 0; i < weakSelf.resArr.count ; i++) {
                          [weakSelf.nameArr addObject: [weakSelf.resArr[i] objectForKey:@"remarks"]];
                      }
                      //得到首字母；处理排序后的数组 用于tableView显示
                      weakSelf.indexArray = [ChineseString IndexArray:weakSelf.nameArr];
                      weakSelf.LetterResultArr = [ChineseString LetterSortArray:weakSelf.resArr];
                      [weakSelf.friendTableView reloadData];
                  }else if ([dic[@"a"] intValue] == -1) {
                      if (TJJiOS8)
                      {
                          UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                          [self presentViewController:Alertview animated:YES completion:nil];
                          UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                              UserConfig *config = [UserConfig sharingUserConfig];
                              [config setHaveLogin:@"lalala"];
                              [config setToken:@"123"];
                              [config setUserHeadData:nil];
                              UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                              LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                              loginVc.quit = YES;
                              [self.navigationController pushViewController:loginVc animated:YES];
                          }];
                          [Alertview addAction:action];
                      }
                      else
                      {
                          UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                          alertView.tag = 97;
                          [alertView show];
                      }
                  }else if ([dic[@"a"] intValue] == 0) {
                      ALERT_VIEW(@"获取失败");
                  }
                  _mbProgressHud.hidden = YES;
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  _mbProgressHud.hidden = YES;
                  ALERT_VIEW(@"信息获取失败");
              }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"friendDetail"]) {
        FriendDetailViewController *friendVc = [segue destinationViewController];
        friendVc.friendInfo = selectDic;
    }
}

- (IBAction)backClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addFriendBtnAction:(id)sender {
    [self performSegueWithIdentifier:@"addFriend" sender:nil];
}

- (IBAction)searchOffButton:(id)sender {
    _searchTextField.text = @"";
    
    _indexArray = [ChineseString IndexArray:_nameArr];
    _LetterResultArr = [ChineseString LetterSortArray:_resArr];
    [_friendTableView reloadData];
    
    [_searchTextField resignFirstResponder];
    
}

#pragma mark  联系人检索 UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length != 0) {
        NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.Name contains[cd] %@",                                     textField.text];
        
        searchResults = [_resArr  filteredArrayUsingPredicate:resultPredicate];
        NSLog(@"搜索结果为===%@",searchResults);
        [searchNameArr removeAllObjects];
        for ( int i = 0; i < searchResults.count ; i++) {
            [searchNameArr addObject: [searchResults[i] objectForKey:@"Name"]];
        }
        _indexArray = [ChineseString IndexArray:searchNameArr];
        _LetterResultArr = [ChineseString LetterSortArray:searchResults];
        
        [_friendTableView reloadData];
    }else {
        
        //得到首字母；处理排序后的数组 用于tableView显示
        _indexArray = [ChineseString IndexArray:_nameArr];
        _LetterResultArr = [ChineseString LetterSortArray:_resArr];
        
        [_friendTableView reloadData];
        
    }
    [textField resignFirstResponder];
    
    return YES;
}



#pragma mark 返回大写首字母
- (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

-(void)judgeBackGroundTime
{
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 97:
        {//重新登录
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        default:
            break;
    }
}
@end
